package demo3;


import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;

public class Text {
    public static void main(String[] args) {
        Callable<Integer> callable = new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                System.out.println("执行运算...");
                int sum = 0;
                // 执行累加操作
                for (int i = 0; i <= 1000; i++) {
                    sum += i;
                }
                // 休眠三秒
                TimeUnit.SECONDS.sleep(3);
                throw new Exception("执行过程中出现了异常....");
//                System.out.println("执行运算完成...");
//                return sum;
            }
        };

        // Callable 要配合FutureTask一起使用 FutureTask用来获取Callable的执行结果
        FutureTask<Integer> futureTask = new FutureTask<>(callable);
        // FutureTask当做构造参数传入到Thread构造方法中
        Thread thread = new Thread(futureTask);
        // 启动线程
        thread.start();
        // 等待结果时间可能被中断  会抛出InterruptedException
        try {
            Integer result = futureTask.get();
            System.out.println("执行结果是：" + result);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
            System.out.println("打印日志：" + e.getMessage());
        }
    }
}
